const
    path = require('path'),
    fs = require('fs'),
    url = require('url'),
    envPublicUrl = process.env.PUBLIC_URL,
    appDirectory = fs.realpathSync(process.cwd()),
    resolveApp = relativePath => path.resolve(appDirectory, relativePath),
    ensureSlash = function (path, needsSlash) {
        const hasSlash = path.endsWith('/');
        if(hasSlash && !needsSlash) {
            return path.substr(0, path.length - 1);
        } else if(!hasSlash && needsSlash) {
            return `${path}/`;
        } else {
            return path;
        }
    },
    getPublicUrl = function (appPackageJson) {
        return envPublicUrl || require(appPackageJson).homepage;
    },
    getServedPath = function (appPackageJson) {
        const
            publicUrl = getPublicUrl(appPackageJson),
            servedUrl = envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/')
        ;

        return ensureSlash(servedUrl, true);
    }
;

const exportsResult = {
    dotenv: resolveApp('.env'),
    appBuild: resolveApp('build'),
    appPublic: resolveApp('public'),
    appHtml: resolveApp('public/index.html'),
    appIndexJs: resolveApp('src/app.js'),
    appPackageJson: resolveApp('package.json'),
    appSrc: resolveApp('src'),
    // yarnLockFile: resolveApp('yarn.lock'),
    // testsSetup: resolveApp('src/setupTests.js'),
    appNodeModules: resolveApp('node_modules'),
    publicUrl: getPublicUrl(resolveApp('package.json')),
    servedPath: getServedPath(resolveApp('package.json')),
};

module.exports = exportsResult;